<template>
    <div class="admin-product">
        <div class="admin-product-header">更新产品</div>
        <div class="admin-product-content">
            <el-form :model="productData" label-width="auto" style="max-width: 1000px">
                <div>
                    <div style="width: 276px;">
                        <el-form-item label="编号">
                            <el-input v-model="productData.serial" />
                        </el-form-item>
                    </div>
                </div>
                <!-- 标题 -->
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="标题（中文）">
                            <el-input v-model="productData.title" />
                        </el-form-item>
                    </div>
                    <div style="margin-left: 270px;">
                        <el-form-item label="标题（英文）">
                            <el-input v-model="productData.title_en" />
                        </el-form-item>
                    </div>
                </div>

                <!-- 价格 -->
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="价格（￥）">
                            <el-input v-model="productData.price" />
                        </el-form-item>
                    </div>
                    <div style="margin-left: 270px;">
                        <el-form-item label="价格（$）">
                            <el-input v-model="productData.price_en" />
                        </el-form-item>
                    </div>
                </div>
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="规格">
                            <el-input v-model="productData.specs" />
                        </el-form-item>
                    </div>
                    <div style="margin-left: 270px;">
                        <el-form-item label="单位">
                            <el-input v-model="productData.unit" />
                        </el-form-item>
                    </div>
                </div>
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="储存方式">
                            <el-input v-model="productData.storage" />
                        </el-form-item>
                    </div>
                    <div style="margin-left: 270px;">
                        <el-form-item label="库存">
                            <el-input v-model="productData.inventory" />
                        </el-form-item>
                    </div>
                </div>
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="简介（中文）">
                            <el-input v-model="productData.introduct" type="textarea" :rows="6" style="width: 300px;" />
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="简介（英文）">
                            <el-input v-model="productData.introduct_en" type="textarea" :rows="6"
                                style="width: 300px;" />
                        </el-form-item>
                    </div>
                </div>
                <div class="form-wrapper">
                    <div>
                        <el-form-item label="使用说明（中文）">
                            <el-input v-model="productData.explain" type="textarea" :rows="6" style="width: 300px;" />
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="使用说明（英文）">
                            <el-input v-model="productData.explain_en" type="textarea" :rows="6"
                                style="width: 300px;" />
                        </el-form-item>
                    </div>
                </div>
                <div class="form-wrapper" style="margin-bottom: 50px;">
                    <div style="float: left;">
                        <span style="margin-right: 50px">一级分类</span>
                        <el-select
                        v-model="firstCategoryTitle"
                        placeholder="请选择一级分类"
                        size="small"
                        style="width: 240px"
                        @change="getSecondCategory"
                        >
                        <el-option
                            v-for="item in firstCategoryData"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                        </el-select>
                    </div>
                    <div style="float: right;">
                        <span style="margin-left: 50px;">二级分类</span>
                        <el-select
                        v-model="secondCategoryTitle"
                        placeholder="请选择二级分类"
                        size="small"
                        style="width: 240px; margin-left: 30px;"
                        @change="getSecondCategoryID"
                        >
                        <el-option
                            v-for="item in secondCategoryData"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                        </el-select>
                    </div>
                </div>
                <!-- 封面 -->
                <div style="margin-bottom: 10px; font-size: 13px;">
                    <span>封面</span>
                </div>
                <div style="display: flex; justify-content: center; border: 1px solid #eee; height: 200px; width: 820px;">
                    <div style="width: 400px;">
                        <div style="width: 400px; margin-bottom: 30px; margin-top: 10px">
                            <el-alert title="横向： 750px * 375px  竖向： 212px * 496px" type="warning" show-icon :closable="false" />
                        </div>
                        <el-upload 
                            class="avatar-uploader" 
                            :action="uploadUrl"
                            :show-file-list="false" 
                            :headers="headersAdmin" 
                            :on-success="handleProductCoverSuccess"
                            :on-remove="handleCoverRemove"
                            style="width: 400px;">
                            <img v-if="productData.cover"
                                :src="productData.cover + '?x-oss-process=image/resize,h_100/quality,q_50'"
                                class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                </div>
                <!-- 文件列表 -->
                <div style="width: 820px; margin-top: 20px;">
                    <div style="margin-bottom: 10px; font-size: 13px;">
                        <span>产品文件</span>
                    </div>
                    <el-upload 
                        class="upload-demo" 
                        drag
                        :action="uploadUrl"
                        :show-file-list="false" 
                        :headers="headersAdmin" 
                        :on-success="handleProductDetailFileSuccess"
                        multiple>
                        <div v-if="detailFileDetail.file_name">{{ detailFileDetail.file_name }}</div>
                        <div v-else>
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                拖拽或 <em>点击选择文件</em> 限制单个文件 pdf/docx 大小控制在5M以内
                            </div>    
                        </div>
                    </el-upload>
                </div>
                <!-- 详解图片列表，最多五张 -->
                <div style="margin-bottom: 5px;margin-top: 10px; font-size: 13px;">
                        <span>产品图片列表</span>
                    </div>
                <div style="margin-top: 20px; height: 160px;padding: 10px; width: 800px;; text-align: center; border: 1px double #eee;">
                    <el-upload 
                        v-model:file-list="productImg" 
                        :action="uploadUrl"
                        :headers="headersAdmin" 
                        list-type="picture-card" 
                        :on-success="handleProductImgSuccess"
                        :on-remove="handleRemove"
                        :limit="5">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                </div>
            </el-form>
            <div style="text-align: center; margin-top: 20px;">
                <el-button type="primary" @click="onSubmitAddProduct">更新</el-button>
                <el-button type="primary"  @click="() => router.push({ path: '/admin/product' })">返回</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Delete, Edit, UploadFilled } from '@element-plus/icons-vue';
import { getProduct, delOssImg, addProduct, firstCategory, secondCategory } from '../../requests/index';
import { useRouter, useRoute } from 'vue-router';
import { uploadUrl } from '@/utils/request';
const route = useRoute();
const router = useRouter();
const loading = ref(true);
const token = window.localStorage.getItem("token");
const headersAdmin = {
    Authorization: `Bearer ${token}`
};
const detailFileDetail = reactive({
    url: "",
    file_name: ""
});
const productImg = ref([]);
const productImgSimple = ref([]);
const productData = reactive({
    title: "",
    title_en: "",
    serial: "",
    price: "",
    price_en: "",
    cover: "",
    inventory: "",
    img: "",
    introduct: "",
    introduct_en: "",
    explain: "",
    explain_en: "",
    detail_file: "",
    recent_id: "",
    storage: "",
    specs: "",
    unit: "",
    img: "",
    first_category_id: 0,
    second_category_id: 0
});
const firstCategoryData = ref([]);
const firstCategoryTitle = ref();
const secondCategoryData = ref([]);
const secondCategoryTitle = ref();
onMounted(() => {
    getFirstCategory();
});
// 获取一级分类
const getFirstCategory = async()=>{
    const res = await firstCategory();
    if (res.status === 2000){
        firstCategoryData.value = res.data;
    }
};

// 获取产品单条记录
const getSingleProduct = async()=>{
    const params = route.query;
    const res = await getProduct({"id": params.id});
    if (res.status === 2000){
        const detailFile = res.data.detail_file;
        if (detailFile){
            const temp = JSON.parse(detailFile);
            detailFileDetail.url = temp.url;
            detailFileDetail.file_name = temp.file_name;
        };
        // 一级二级产品分类
        firstCategoryTitle.value = res.data.first_category_id;
        getSecondCategoryTemp(res.data.first_category_id);
        secondCategoryTitle.value = res.data.second_category_id;
        // 图片列表
        const imgList = res.data.img;
        if (imgList){
            const imgListTemp = JSON.parse(imgList)
            productImg.value = imgListTemp;
            productImgSimple.value = imgListTemp;
        };
        productData.id = res.data.id;
        productData.title = res.data.title;
        productData.title_en = res.data.title_en;
        productData.serial = res.data.serial;
        productData.price = res.data.price;
        productData.price_en = res.data.price_en;
        productData.cover = res.data.cover;
        productData.inventory = res.data.inventory;
        productData.introduct = res.data.introduct;
        productData.introduct_en = res.data.introduct_en;
        productData.explain = res.data.explain;
        productData.explain_en = res.data.explain_en;
        productData.detail_file = res.data.detail_file;
        productData.recent_id = res.data.recent_id;
        productData.storage = res.data.storage;
        productData.specs = res.data.specs;
        productData.unit = res.data.unit;
        productData.img = res.data.img;
        productData.second_category_id = res.data.second_category_id;
    }
}
getSingleProduct();

// 进入页面
const getSecondCategoryTemp = async(value)=>{
    secondCategoryData.value = [];
    productData.first_category_id = value;
    const res = await secondCategory({"id": value});
    if (res.status === 2000){
        secondCategoryData.value = res.data;
    }else{
        ElMessage.error("获取二级分类失败");
    };
};
// 选择一级分类之后处理
const getSecondCategory = async(value)=>{
    secondCategoryData.value = [];
    productData.first_category_id = value;
    const res = await secondCategory({"id": value});
    if (res.status === 2000){
        secondCategoryData.value = res.data;
        secondCategoryTitle.value = null;
    }else{
        ElMessage.error("获取二级分类失败");
    };
};
// 获取二级分类的ID
const getSecondCategoryID = (value)=>{
    productData.second_category_id = value;
}

// 封面图片上传成功
const handleProductCoverSuccess = async(response, uploadFilled) =>{
    if (response.status === 2000) {
        if (productData.cover){
            const res = await delOssImg({"img":productData.cover});
        };
        productData.cover = response.file;
    } else {
        ElMessage.error(response.msg);
    };
};
// 删除封面
const handleCoverRemove = async(response, fileList)=>{
    const res = await delOssImg({"img": file.response.file});
    if (res.status === 2000){
        productData.cover = ""
    }else{
        ElMessage.error("删除封面失败");
    }
}
// 产品文件上传成功
const handleProductDetailFileSuccess = async(response, uploadFilled)=>{
    if (response.status === 2000) {
        if (productData.detail_file){
            const res = await delOssImg({"img":productData.detail_file});
            detailFileDetail.file_name = "";
            detailFileDetail.url = "";
        }
        detailFileDetail.file_name = response.file_name;
        detailFileDetail.url = response.file;
        productData.detail_file = response.file;
    } else {
        ElMessage.error(response.msg);
    }
};
// 产品图片列表
const handleProductImgSuccess = async(response, uploadFilled)=>{
    if (response.status === 2000){
        productImgSimple.value.push({"name": response.file_name, 'url': response.file});
    }else{
        ElMessage.error(response.msg);
    }
};
// 产品图片列表  删除图片
const handleRemove = async(file, fileList)=>{
    const res = await delOssImg({"img": file.response.file});
    if (res.status === 2000){
        const index = productImgSimple.value.findIndex(item => item.url === file.response.file);
        if (index != -1){
            productImgSimple.value.splice(index, 1);
        };
        console.log(productImgSimple.value);
    }else{
        ElMessage.error("删除失败");
    };
    console.log(productImg.value);
};
// 提交新增产品
const onSubmitAddProduct = async()=>{
    productData.detail_file = JSON.stringify(detailFileDetail);
    productData.img = JSON.stringify(productImgSimple.value);
    const res = await addProduct(productData);
    if (res.status === 2000){
        ElMessage.success("新增产品成功");
        router.push({path: "/admin/product"});
    }else{
        ElMessage.error("新增产品失败");
    };
};
</script>

<style scoped>
.admin-product-header {
    margin-top: 20px;
    margin-left: 20px;
    height: 40px;
    line-height: 40px;
    background-color: #F9F9F9;
    padding-left: 20px;
    padding-right: 20px;
}

.admin-product-content {
    margin-top: 80px;
    margin-bottom: 50px;
    margin-left: 20px;
}

.admin-product {
    display: flex;
    text-align: center;
    min-height: 100px;
}

.form-wrapper > div {
    display: inline-block;
}
</style>